package com.example.emergencyattempt01.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.example.emergencyattempt01.R;
import com.example.emergencyattempt01.activity.administrator_activity.Administrator_main_structure;
import com.example.emergencyattempt01.activity.ex.GifDialogFragment;
import com.example.emergencyattempt01.activity.student_activity.Student_Main_Structure;
import com.example.emergencyattempt01.activity.utils.NetWorkUtils;
import com.example.emergencyattempt01.activity.utils.ServerMessage;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.FileNotFoundException;
import java.io.IOException;

public class LoginActivity extends AppCompatActivity {
    EditText uidField;
    EditText passwordField;
    Button loginBtn;
    long uid;
    String password;


    final int permittedNoCheckCount=2;// 用于设置允许免检的次数
    SharedPreferences personal_SharePreference;
    Handler handlerForLogin=new Handler()
    {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what)
            {
                case LOGIN_SUCCESS:
                    ServerMessage message=(ServerMessage) msg.obj;
                    String fromServer=(String) message.getFromServer();
                    try {
                        JSONObject object=new JSONObject(fromServer);

                        long uid=object.getLong("uid");
                        String userName=object.getString("userName");
                        String userType=object.getString("userType");
                        String identity=object.getString("identity");
                        String institute=object.getString("institute");
                        int ownBooks=object.getInt("ownBooks");
                        String password=object.getString("password");


                        SharedPreferences.Editor editor=personal_SharePreference.edit();
                        editor.putInt("loginWithoutCheckCount",permittedNoCheckCount);//设置允许无检登录次数
                        editor.putLong("uid",uid);
                        editor.putString("userName",userName);
                        editor.putInt("ownBooks",ownBooks);
                        editor.putString("userType",userType);
                        editor.putString("institute",institute);
                        editor.putString("identity",identity);
                        editor.putString("password",password);
                        editor.commit();//不要忘记提交数据*/

                        // 设置一个跳转，同时把上述数据加进去
                        // 这里要根据userType决定到底跳转到哪个界面
                        if(userType.equals("学生"))
                        {
                            Intent intent=new Intent(LoginActivity.this, Student_Main_Structure.class);
                            startActivity(intent);
                        }
                        else
                        {
                            Intent intent=new Intent(LoginActivity.this, Administrator_main_structure.class);
                            startActivity(intent);
                        }
                        finish();
                        Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                    }catch (JSONException e){e.printStackTrace();}
                    break;
                case LOGIN_FAIL:
                    Toast.makeText(LoginActivity.this,"登录失败,网络大概有些问题...",Toast.LENGTH_SHORT).show();
                    break;
                case LOGIN_WRONG_DATA:
                    Toast.makeText(LoginActivity.this,"您的密码和uid不匹配，请重新输入",Toast.LENGTH_SHORT).show();
                    break;
                case LOGIN_NO_SUCH_USER:
                    Toast.makeText(LoginActivity.this,"不存在该用户，请重新输入",Toast.LENGTH_SHORT).show();
                    break;
            }
            loading.dismiss();
        }
    };
    final int LOGIN_SUCCESS=0x024;
    final int LOGIN_WRONG_DATA=0x026;
    final int LOGIN_FAIL=0x025;
    final int LOGIN_NO_SUCH_USER=0x028;

    GifDialogFragment loading;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_layout);
        initPage();
        setLoginCheck();
         // 设置监听
        setLoginBtn();

    }

    private void setLoginBtn() {
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 先判断是否输入合法，合法再进行传输
                if(!uidField.getText().toString().trim().equals("")&&!passwordField.getText().toString().trim().equals(""))
                {
                    // 涉及网络，另开线程
                    new Thread()
                    {
                        @Override
                        public void run() {
                            try {
                                // 打开一个加载界面
                                loading=new GifDialogFragment();
                                loading.show(getSupportFragmentManager(),"register_dialog_loading");
                                try {
                                    Thread.sleep(5000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }

                                collectMessage();
                                // 加工成JSONObject
                                JSONObject object=new JSONObject();

                                object.put("uid",uid);
                                object.put("password",password);
                                String toServer=String.valueOf(object);
                                // 调用网络请求方法，得到返回数据
                                ServerMessage serverMessage=NetWorkUtils.getInstance().create(toServer,"/login");
                                int code=serverMessage.getRespondCode();// 获取返回码
                                if(code==200)// 代表发送成功
                                {
                                    String fromServer=(String) serverMessage.getFromServer();// 获取返回的数据
                                    JSONObject object1=new JSONObject(fromServer);
                                    boolean isMatched=object1.getBoolean("find");
                                    if(isMatched)
                                    {
                                        Message message=new Message();
                                        message.what=LOGIN_SUCCESS;
                                        message.obj=serverMessage;
                                        handlerForLogin.sendMessage(message);
                                    }
                                    else {
                                        Message message=new Message();
                                        message.what=LOGIN_WRONG_DATA;
                                        handlerForLogin.sendMessage(message);
                                    }
                                }
                                else {
                                    Message message=new Message();
                                    message.what=LOGIN_FAIL;
                                    handlerForLogin.sendMessage(message);
                                }
                            }catch (JSONException e){
                                e.printStackTrace();
                                Message message=new Message();
                                message.what=LOGIN_FAIL;
                                handlerForLogin.sendMessage(message); }
                            catch (FileNotFoundException e)// 也是一种不匹配的返回方式
                            /**
                             * 此段是我测试后端的时候发现的一个特点
                             * 不知后端具体怎么完成查验工作的，不过貌似只要uid不存在，就会报这样一个异常
                             * 对于返回find的服务，都对标这个进行处理吧
                             * 2020/12/19 董延涛
                             */
                            {
                                e.printStackTrace();
                                Message message=new Message();
                                message.what=LOGIN_NO_SUCH_USER;
                                handlerForLogin.sendMessage(message);
                            }
                            catch (IOException e)
                            {
                                e.printStackTrace();
                                Message message=new Message();
                                message.what=LOGIN_FAIL;
                                handlerForLogin.sendMessage(message);
                            }
                        }
                    }.start();
                }
                else
                {
                    Toast.makeText(LoginActivity.this,"输入不合法，请重新输入",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    private void collectMessage() {
        uid=Long.parseLong(uidField.getText().toString().trim());
        password=passwordField.getText().toString().trim();
    }

    private void initPage() {
        uidField=findViewById(R.id.login_uid);
        passwordField=findViewById(R.id.login_password);
        loginBtn=findViewById(R.id.login_btn);
    }
    private void setLoginCheck() {
        personal_SharePreference=getSharedPreferences("personal_information",MODE_PRIVATE);
        // 得到当前支持的无需登录即可进入系统的次数
        // 如果没有存入的话，则默认为0，由此决定是否直接跳转至主页
        int count=personal_SharePreference.getInt("loginWithoutCheckCount",0);
        Log.i("loginCount",count+"");
        if(count>0)
        {
            // 表示最近已经验证过了，无需再验证一次
//修改前必须先创建一个editor
            SharedPreferences.Editor editor=personal_SharePreference.edit();
            editor.putInt("loginWithoutCheckCount",count-1);
            editor.commit();// 切勿忘记更新！！
            // 跳转
            String userType=personal_SharePreference.getString("userType",null);
            if(userType.equals("学生"))
            {
                Intent intent=new Intent(LoginActivity.this,Student_Main_Structure.class);
                startActivity(intent);
            }
            else
            {
                Intent intent=new Intent(LoginActivity.this, Administrator_main_structure.class);
                startActivity(intent);
            }
        }
        else
        {
            // 提示登录已到期，需重新登录，不予直接跳转
            Toast.makeText(LoginActivity.this,"登录已到期，请重新登录",Toast.LENGTH_SHORT).show();

        }
    }

}